/*
 * @Description: 主页
 * @Author: fhw
 * @Date: 2022-12-29 15:24:12
 */
import {
	defineComponent,
	h,
	onMounted,
	provide,
	reactive,
	ref,
	shallowRef,
	watch,
	computed,
	nextTick,
	inject,
	watchEffect,
} from 'vue'
import Chat, { toScrollBottom } from './components/chat'
import Contacts from './components/addressList'
import './style.scss'
import { IconFriends, IconNews } from '@/components/icon'
import { clone, equals, isEmpty } from 'ramda'
import { ChatRecord, ChatUserGroup, HistorySession, User } from '@/interface'
import { FormFollow } from '@/components'
import UserInfo from '@/components/user/userInfo'
import { UserInfoModalState } from './interface'
import { isTrue } from '@/utils/tools'
import { UserOutlined } from '@ant-design/icons-vue'
import { BasicDataModule } from '@/store/modules/basicData'
import { getChatCommunication } from './util'
import { Socket } from 'socket.io-client'
export default defineComponent({
	setup() {
		onMounted(() => {
			getUserInfo()
			// 获取历史会话
			if (!isTrue(BasicDataModule.historySession)) {
				BasicDataModule.getHistorySession()
			}
		})
		// 通讯
		const socket = inject('socket') as Socket
		// 好友备注集合
		const friendsRemarksMap = ref<Map<string, string>>(new Map())
		// 聊天列表
		const contacts = computed(() => {
			return BasicDataModule.contacts
		})
		// 历史会话
		const historySession = computed<HistorySession[]>(() => {
			return BasicDataModule.historySession
		})
		watch(
			() => BasicDataModule.contacts,
			(contacts) => {
				if (!isEmpty(contacts)) {
					const userId = localStorage.getItem('userId') as string
					// 注册群聊
					contacts.forEach((item) => {
						if (equals(item.classType, 2)) {
							socket?.emit('groupChatLogin', { group_id: item.group_id, userId })
						}
					})
				}
			},
			{
				deep: true,
				immediate: true,
			}
		)
		watchEffect(() => {
			if (!isEmpty(historySession)) {
				historySession.value.forEach((item) => {
					friendsRemarksMap.value?.set(item.historicalUserSessionsId as string, item.chatUserFriend?.remarks as string)
					getChatCommunication(item)
				})
			}
		})
		// 组件切换
		const component = shallowRef(Chat)
		const userId = localStorage.getItem('userId') as string

		// 用户信息
		const userInfo = ref<User>({})
		provide('userInfo', userInfo)
		provide('friendsRemarksMap', friendsRemarksMap)
		// 发送消息切换指定聊天用户
		provide('onSendMessage', onSendMessage)
		const userInfoModalState = reactive<UserInfoModalState>({
			visible: false,
			loading: false,
			user: {} as User,
		})
		async function getUserInfo() {
			const { success, data } = await API.blog.chatUser.getUserInfo.request({ id: userId })
			if (success) {
				userInfo.value = clone(data)
				BasicDataModule.getContacts()
			}
		}
		// 更新联系人最新消息
		function updateLatestNews(chatRecord: ChatRecord) {
			historySession.value.forEach((item) => {
				if (equals(item.historicalUserSessionsId, chatRecord.to_userId || chatRecord.group_id)) {
					item.latestNews = clone(chatRecord)
				}
			})
		}
		// 监听未读消息并更新消息提示
		watch(
			() => BasicDataModule.chatUnreadMessage,
			(chatUnreadMessage) => {
				historySession.value.forEach((item) => {
					if (!chatUnreadMessage[item.historicalUserSessionsId as string]) return
					const { latestNews } = chatUnreadMessage[item.historicalUserSessionsId as string]
					if (isTrue(latestNews)) {
						item.latestNews = clone(latestNews)
					}
				})
			},
			{
				deep: true,
			}
		)
		// 未读总数量
		const unreadTotalCount = computed(() => {
			let count = 0
			const ids = historySession.value
				.filter((item) => equals(String(item.doNotDisturb), '1'))
				.map((item) => item.historicalUserSessionsId)
			for (const key in BasicDataModule.chatUnreadMessage) {
				if (ids.includes(key)) {
					count += BasicDataModule.chatUnreadMessage[key].count ?? 0
				}
			}
			return count
		})
		// 设置未读数量位置
		const offset = computed(() => {
			if (unreadTotalCount.value <= 99) {
				return [-14, 0]
			} else if (unreadTotalCount.value <= 999) {
				return [-24, 0]
			} else {
				return [-34, 0]
			}
		})
		// 发送聊天用户数据
		const sendMessageUserState = ref<HistorySession>()
		function onSendMessage(user: User | ChatUserGroup) {
			if (!isTrue(user)) {
				sendMessageUserState.value = undefined
				return
			}
			if (equals((user as ChatUserGroup).classType, 1)) {
				// 获取用户好友信息
				const chatUserFriend = contacts.value.find((item) => equals(item.id, user.id))
				sendMessageUserState.value = {
					userId: Number(userId),
					historicalUserSessionsId: String(user.id),
					friends: clone(user),
					chatUserFriend: chatUserFriend,
					latestNews: clone(chatUserFriend?.latestNews),
					latestNewsId: chatUserFriend?.latestNews?.id,
				}
			} else {
				const userGroup = user as ChatUserGroup
				// 获取群聊信息
				const chatUserGroup = contacts.value.find((item) => equals(item?.groupChat?.group_id, userGroup.group_id))
				sendMessageUserState.value = {
					userId: Number(userId),
					historicalUserSessionsId: String(userGroup.group_id),
					friends: clone(user),
					chatUserGroup,
					latestNews: clone(chatUserGroup?.latestNews),
					latestNewsId: chatUserGroup?.latestNews?.id,
				}
			}

			BasicDataModule.getHistorySession()
			toChat()
		}
		function toChat() {
			component.value = Chat
			nextTick(() => {
				toScrollBottom()
			})
		}
		function onDeleteHistorySession(index: number) {
			historySession.value.splice(index, 1)
		}
		return () => (
			<div id="chat">
				<div class="chat-nav">
					<div
						class="chat-user-headPortrait"
						onClick={() => {
							userInfoModalState.visible = true
						}}
					>
						{isTrue(userInfo.value.headimgurl) ? (
							<img src={userInfo.value.headimgurl} alt="" />
						) : (
							<a-avatar shape="square" size={40} icon={<UserOutlined />} />
						)}
					</div>
					<ul>
						<li onClick={toChat}>
							<IconNews active={equals(component.value, Chat)} />
							<a-badge count={unreadTotalCount.value ?? 0} overflow-count={999} offset={offset.value} />
						</li>
						<li
							onClick={() => {
								component.value = Contacts
							}}
						>
							<a-badge
								count={BasicDataModule.unreadFriendsTotalCount ?? 0}
								overflow-count={999}
								offset={offset.value}
							/>
							<IconFriends active={equals(component.value, Contacts)} />
						</li>
					</ul>
				</div>
				<div class="chat-right">
					{h(component.value, {
						onUpdateLatestNews: updateLatestNews,
						onSendMessage,
						sendMessageUserState: sendMessageUserState.value,
						onDeleteHistorySession,
					})}
				</div>
				<FormFollow v-model={[userInfoModalState.visible, 'visible']}>
					<UserInfo dataSource={userInfo.value} />
				</FormFollow>
			</div>
		)
	},
})
